package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 请求处理类
 */

@RestController
@RequestMapping("/books")
public class BookController {

    /**
     * 业务层return boolean，表现层return方法
     */
    //注入业务层接口
    @Autowired
    private BookService bookService;

    /**
     * 保存图书信息
     */
    @PostMapping
    public Result save(@RequestBody Book book) {

        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR , "" , flag);
    }

    /**
     * 修改图书信息
     */
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);

        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR , "" , flag);
    }

    /**
     * 删除图书信息
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);

        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR , "" , flag);
    }

    /**
     * 根据ID查找图书信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);

        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book !=null ? "" : "数据查询失败，请重试！";

        return new Result(code , msg , book);
    }

    /**
     * 查询所有图书信息
     */
    @GetMapping
    public Result getAll() {
        List<Book> bookList = bookService.getAll();     //booklist为null而不是为空，因为可能本来就没数据

        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList !=null ? "" : "数据查询失败，请重试！";

        return new Result(code , msg , bookList);
    }
}
